package day21;

import java.io.*;

public class IO02 {
    public static void main(String[] args) throws IOException {
        File srcDir = new File("C:\\Users\\Admin\\Desktop\\Directory");
        File destDir = new File("C:\\Users\\Admin\\Desktop\\CopiedDirectory"); // 明确目标目录
        copyDirectory(srcDir, destDir);
    }

    private static void copyDirectory(File srcDir, File destDir) throws IOException {
        if (!destDir.exists() && !destDir.mkdirs()) {
            throw new IOException("无法创建目标目录: " + destDir.getPath());
        }

        File[] files = srcDir.listFiles();
        if (files == null) return;

        for (File file : files) {
            File destFile = new File(destDir, file.getName());
            if (file.isDirectory()) {
                copyDirectory(file, destFile); // 递归处理子目录
            } else {
                copyFile(file, destFile);      // 复制文件
            }
        }
    }

    private static void copyFile(File srcFile, File destFile) throws IOException {
        try (InputStream in = new FileInputStream(srcFile);
             OutputStream out = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[1024 * 1024 * 5];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}